package com.gaogzhen.datastructure.graph.undirected;

import com.gaogzhen.datastructure.stack.Stack;
import edu.princeton.cs.algs4.Graph;

import java.util.Iterator;

/**
 * 检测环
 * @author: Administrator
 * @createTime: 2023/03/10 19:27
 */
public class Cycle {
    private boolean[] marked;
    private int[] edgeTo;
    private Stack<Integer> cycle;

    /**
     * 检测是否有环，如果有给出环路
     *
     * @param G the undirected graph
     */
    public Cycle(Graph G) {
        // 如果有平行边，返回
        if (hasParallelEdges(G)) {
            return;
        }

        // don't need special case to identify self-loop as a cycle
        // if (hasSelfLoop(G)) return;

        marked = new boolean[G.V()];
        edgeTo = new int[G.V()];
        dfs(G);
    }

    private void dfs(Graph G) {
        Stack<Node> stack = new Stack<>();
        for (int v = 0; v < G.V(); v++) {
            if (!marked[v]) {
                if (dfs(G, -1, v, stack) ) {
                    return;
                }
            }
        }
    }

    /**
     * 深度优先搜索环路
     *
     * @param G     无向图
     * @param u
     * @param v
     * @param stack
     */
    private boolean dfs(Graph G, int u, int v, Stack<Node> stack) {
        marked[v] = true;
        Iterable<Integer> adj = G.adj(v);
        if (adj != null) {
            stack.push(new Node(v, u, adj.iterator()));
        }

        while (!stack.isEmpty()) {
            Node c = stack.pop();

            while (c.adj.hasNext()) {
                Integer w = c.adj.next();
                if (!marked[w]) {
                    marked[w] = true;
                    edgeTo[w] = c.v;
                    if (c.adj.hasNext()) {
                        stack.push(c);
                    }
                    Iterable<Integer> adjW = G.adj(w);
                    if (adjW != null) {
                        stack.push(new Node(w, c.v, adjW.iterator()));
                    }
                    break;
                }

                // check for cycle (but disregard reverse of edge leading to v)
                else if (w != c.parent) {
                    cycle = new Stack<>();
                    for (int x = c.v; x != w; x = edgeTo[x]) {
                        cycle.push(x);
                    }
                    cycle.push(w);
                    cycle.push(c.v);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检测无向图G是否有子环
     * @param G
     * @return
     */
    private boolean hasSelfLoop(Graph G) {
        for (int v = 0; v < G.V(); v++) {
            for (int w : G.adj(v)) {
                if (v == w) {
                    cycle = new Stack<Integer>();
                    cycle.push(v);
                    cycle.push(v);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检测无向图G是否有平行边
     * @param G
     * @return
     */
    private boolean hasParallelEdges(Graph G) {
        marked = new boolean[G.V()];

        for (int v = 0; v < G.V(); v++) {

            // check for parallel edges incident to v
            for (int w : G.adj(v)) {
                if (marked[w]) {
                    cycle = new Stack<Integer>();
                    cycle.push(v);
                    cycle.push(w);
                    cycle.push(v);
                    return true;
                }
                marked[w] = true;
            }

            // reset so marked[v] = false for all v
            for (int w : G.adj(v)) {
                marked[w] = false;
            }
        }
        return false;
    }

    /**
     * 是否有环
     *
     * @return {@code true} if the graph has a cycle; {@code false} otherwise
     */
    public boolean hasCycle() {
        return cycle != null;
    }

    /**
     * 如果有环，返回环路
     * @return a cycle if the graph {@code G} has a cycle,
     *         and {@code null} otherwise
     */
    public Iterable<Integer> cycle() {
        return cycle;
    }



    static class Node {

        /**
         * 顶点索引
         */
        private int v;

        /**
         * 顶点父结点索引
         */
        private int parent;

        /**
         * 顶点邻接表
         */
        private Iterator<Integer> adj;

        public Node(int v, int parent, Iterator<Integer> adj) {
            this.v = v;
            this.parent = parent;
            this.adj = adj;
        }
    }
}
